"""Splits query results list into multiple sublists for template display."""

from django.template import Library, Node
from django.template import TemplateSyntaxError

register = Library()

class SplitterNode(Node):
    def __init__(self, results, cols, new_results):
        self.results, self.cols, self.new_results = results, cols, new_results

    def split_seq(self, results, cols="2"):
        res = []


        cols = map( int, cols.split(":"))

        current_col_index = 0
        index = 0
        _res = []
        for r in results:
            _res += [r]
            index+=1
            if index>=cols[current_col_index]:
                current_col_index+=1
                if current_col_index>=len(cols):
                    current_col_index = len(cols) - 1
                index = 0
                res += [_res]
                _res = []

        if len(_res):
            res += [_res]


        print res
        return res


    def render(self, context):
        context[self.new_results] = self.split_seq(context[self.results], self.cols)
        return ''

def list_split(parser, token):
    """Parse template tag: {% list_to_colums results as new_results 2 %}"""
    bits = token.contents.split()
    if len(bits) != 5:
        raise TemplateSyntaxError, "list_split results as new_results 2"
    if bits[2] != 'as':
        raise TemplateSyntaxError, "second argument to the list_split tag must be 'as'"
    return SplitterNode(bits[1], bits[4], bits[3])

list_split = register.tag(list_split)


